<template>
  <div class="page-register-step">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="phone"
          placeholder="请输入手机号码"
          maxlength="11"
          :formatter="formatterPhone"
          :rules="[{ required: true, message: '请输入手机号码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button
          :disabled="phoneButtonIsDisabled"
          round
          block
          type="primary"
          native-type="submit"
        >
          下一步
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { useRegisterStore } from "@/stores/register";

const registerStore = useRegisterStore();
// PS： 不要直接对 store 实例做 解构赋值，因为这个 store 实例是一个 proxy .会丢失响应式。
//      正确的做法是：toRef  storeToRefs
// const { phone } = registerStore;
const { phone, phoneButtonIsDisabled } = storeToRefs(registerStore);

// 输入框格式化函数
const formatterPhone = (value: string) => {
  // 需要返回格式化之后的内容
  return value.replace(/[a-z]/g, "").replace(/[A-Z]/g, "");
};

// 提交
const router = useRouter();
const onSubmit = async () => {
  // 之前在 NaiveUI 需要主动触发表单校验，这里的 Vant 不需要
  // console.log("onSubmit");
  // 调用 store.oneSubmit
  await registerStore.oneSubmit();
  // 一切OK,在这处理路由跳转
  console.log("OK");
  router.push({ name: "step-2" });
};
</script>
